<template>
  <div class="auth-login">
    <div class="auth-login-header">⚡Hi，欢迎登录</div>
    <a-form :model="form" :rules="rules" ref="formRef">
      <a-form-item name="username">
        <a-input size="large" placeholder="请输入账户或是手机号码" v-model:value="form.username" allow-clear>
          <template #prefix><user-outlined/></template>
        </a-input>
      </a-form-item>
      <a-form-item name="password">
        <a-input-password size="large" v-model:value="form.password" placeholder="请输入您的密码" allow-clear>
          <template #prefix><lock-outlined/></template>
        </a-input-password>
      </a-form-item>
      <a-form-item name="captcha">
        <a-flex :gap="16">
          <a-input size="large" v-model:value="form.captcha" style="flex: 1" placeholder="请输入验证码">
            <template #prefix><verified-outlined/></template>
          </a-input>
          <div class="captcha">
            <UseCaptcha ref="captchaRef" v-model:code="form.code"/>
          </div>
        </a-flex>
      </a-form-item>
      <form-item layout="vertical" class="margin-bottom">
        <a-flex justify="space-between" align="center">
          <a-checkbox name="remember" v-model:checked="form.remember">记住密码</a-checkbox>
          <a href="javascript:" @click="clickForgetPassword">忘记密码</a>
        </a-flex>
      </form-item>
      <a-form-item>
        <a-button block size="large" type="primary" :loading="loading" @click="onLogin">登录</a-button>
      </a-form-item>
      <a-flex>
        <span>
          没有账号？
          <router-link to="/register">创建账号</router-link>
        </span>
      </a-flex>
    </a-form>
  </div>

</template>

<script setup lang="ts">
import FormItem from "@/components/FormItem.vue";
import {UserOutlined,LockOutlined,VerifiedOutlined} from "@ant-design/icons-vue";
import {type FormInstance, message} from "ant-design-vue";
import UseCaptcha from "@/components/UseCaptcha.vue";
import {reactive, ref} from "vue";
import type {Rule} from "ant-design-vue/es/form";
import {login} from "@/services/api/auth.ts";
import {useRouter} from "vue-router";

const router = useRouter()
const formRef = ref<FormInstance>()
const captchaRef = ref<InstanceType<typeof UseCaptcha>>()
const form = reactive<loginForm>({
  username: '',
  password: '',
  captcha: '',
  remember: false,
  code: ''
})
/**
 * 验证码校验
 * @param _rule
 * @param value
 */
const checkCaptcha = async (_rule:Rule,value:string) => {
  if (!value){
    return Promise.reject('请输入验证码')
  }else {
    if (!captchaRef.value?.validateCaptcha(value)){
      return Promise.reject('验证码错误')
    }else {
      return Promise.resolve()
    }
  }
}
/**
 * 表单验证规则
 */
const rules = {
  username: [{required: true, message: '请输入账户或是手机号码', trigger: 'blur'}],
  password: [ {required: true, message: '请输入您的密码', trigger: 'blur'}],
  captcha: [{required: true, validator: checkCaptcha, trigger: 'blur'}]
}
// 按钮loading状态
const loading = ref<boolean>(false)
const clickForgetPassword = () => {
  message.info('忘记密码功能正在开发中，敬请期待...')
}
// 登录
const onLogin = async () => {
  loading.value = true
  try {
    await formRef.value?.validate()
    const logoStatus = message.loading('登录中...',0)
    const data = {
      username: form.username,
      password: form.password,
    }
    const res:ApiResponse<LoginResponse> = await login(data)
    if(res.code === 200 && res.data){
      if (form.remember){
        localStorage.setItem('userInfo',JSON.stringify(res.data.userinfo))
        localStorage.setItem('token',res.data.token)
      }else {
        localStorage.setItem('userInfo',JSON.stringify(res.data.userinfo))
        sessionStorage.setItem('token',res.data.token)
      }
      setTimeout(logoStatus,500)
      setTimeout(()=>message.success(res.message),600)
      setTimeout(()=> router.push('/'),3000)
    }else {
      message.error(res.message)
    }
  }catch{
    message.warn('登录失败！请检查重试...')
  }finally {
    setTimeout(()=>{
      captchaRef.value?.refreshCaptcha()
      loading.value = false
    },3000)
  }
}
</script>

<style scoped>
  .auth-login{
    padding: 24px 32px;
  }
  .auth-login-header {
    font-size: 24px;
    margin-bottom: var(--space);
  }
  .captcha {
    width: 120px;
    height: 40px;
    border-radius: var(--radius);
    overflow: hidden;
    border:1px solid #d9d9d9;
  }
</style>